$(function () {
    let buttonGroup = [
        {
            id: 'btn_add_payment',
            size: 'small',
            text: '新增付款',
            iconCls: 'icon-add',
            plain: true,
            onClick: btn_add_payment
        },
        {
            id: 'btn_modify_payment',
            size: 'small',
            text: '修改付款',
            iconCls: 'icon-edit',
            plain: true,
            onClick: btn_modify_payment
        },
        {
            id: 'btn_cancel_filter',
            size: 'small',
            text: '清除过滤',
            iconCls: 'icon-clear',
            plain: true,
            onClick: btn_cancel_filter
        },
        {
            id: 'btn_export',
            size: 'small',
            text: '导出Excel',
            iconCls: 'icon-page_excel',
            plain: true,
            onClick: btn_export_excel
        },
        {
            id: 'btn_print',
            size: 'small',
            text: '打印',
            iconCls: 'icon-print',
            plain: true,
            onClick: btn_print
        },
        {
            id: 'btn_grid_columns',
            size: 'small',
            text: '列',
            iconCls: 'icon-text_columns',
            plain: true,
            onClick: btn_open_column_list
        },
        {
            id: 'btn_close', size: 'small', text: '关闭', iconCls: 'icon-no', onClick: btn_close,
            plain: true
        },
    ];
    buttonGen($('#north'), buttonGroup);
    bindEnterEvents();
    let kGrid = $('#v_grid').data('kendoGrid');
    var options = kGrid.getOptions();
    if (options.columns.length > 0)
        initCombobox(options)
})
const materialColumns = [
    {title: 'id', field: 'id', hidden: true,},
    {
        title: '制单日期',
        field: 'orderDate',
        id: 'orderDateInput',
        editor: {type: 'datebox', options: {value: getCurrentDate()}}
    },
    {title: '单据编号', field: 'orderCode', editor: {type: 'textbox', options: {required: false, readonly: true}}},
    {
        title: '单据类型', field: 'billType', id: 'billTypeInput', editor: {
            type: 'combobox', options: {
                url: 'billType/listQuery',
                queryParams: {storageId: 1, accessMode: 1},
                method: 'GET',
                textField: 'billTypeName', valueField: 'id',
                panelHeight: 200,
                required: true,
                onLoadSuccess: function () {
                    $(this).combobox('options').limitToList = true;
                    let _data = $(this).combobox('getData') || [];
                    let _opts = $(this).combobox('options');
                    if (_data instanceof Array && !$(this).combobox('getValue') && _data.length > 0) {
                        for (let i of _data) {
                            if (i['isSelected']) {
                                $(this).combobox('setValue', i[_opts.valueField]);
                                break;
                            }
                        }
                    }
                }
            }
        }
    },
    {
        title: '付款方式', field: 'accountType', id: 'accountTypeInput', editor: {
            type: 'combobox', options: {
                url: 'materialOrder/listQuery/accountType',
                method: 'GET',
                textField: 'value', valueField: 'value',
                panelHeight: 'auto',
                required: true,
                value: '预付',
                onLoadSuccess: function () {
                    $(this).combobox('options').limitToList = true;
                    if (!$(this).combobox('getValue')) {
                        let options = $(this).combobox('options');
                        let loadData = $(this).combobox('getData') || [];
                        if (loadData.length > 0)
                            $(this).combobox('setValue', loadData[0][options.valueField]);
                    }
                }
            }
        }
    },
    {
        title: '供应商', field: 'supplierId', editor: {
            type: 'combobox', options: {
                url: 'supplier/listQuery',
                method: 'GET',
                textField: 'supplierName', valueField: 'id',
                panelHeight: 200,
                required: true,
                onLoadSuccess: function () {
                    $(this).combobox('options').limitToList = true;
                }
            }
        }
    },
    {
        title: '原料规格', field: 'materialSpec', editor: {
            type: 'combobox', options: {
                url: 'specification/listQuery',
                method: 'GET',
                textField: 'specName',
                valueField: 'specName',
                panelHeight: 200,
                required: true,
            }
        }
    },
    {title: '批号', field: 'batchNum', editor: {type: 'textbox', options: {required: false}}},
    {title: '件数', field: 'boxAmount', editor: {type: 'numberbox', options: {precision: 1, required: false}}},
    // {title: '入库匹数', field: 'inputAmount', editor: {type: 'numberbox', options: {precision: 0, required: true}}},
    {
        title: '重量',
        id: 'inputKiloId',
        field: 'inputKilo',
        editor: {type: 'numberbox', options: {precision: 1, required: true}}
    },
    {title: '单价', id: 'priceId', field: 'price', editor: {type: 'numberbox', options: {precision: 2, required: false}}},
    {
        title: '金额',
        id: 'inputMoneyId',
        field: 'inputMoney',
        editor: {type: 'numberbox', options: {precision: 2, readonly: true}}
    },
    {title: '备注', field: 'remarks', editor: {type: 'textbox', options: {required: false}}},
    {
        title: '制单人',
        field: 'createUserId',
        editor: {
            type: 'combobox',
            options: {
                readonly: true,
                url: 'sysUser/query',
                method: 'GET',
                textField: 'userName',
                valueField: 'id',
                onLoadSuccess: function () {
                    $(this).combobox('options').limitToList = true;
                }
            }
        }
    },
];
const materialOutboundColumns = [
    {title: 'id', field: 'id', hidden: true,},
    {title: '制单日期', field: 'orderDate', editor: {type: 'datebox', options: {value: getCurrentDate()}}},
    {title: '单据编号', field: 'orderCode', editor: {type: 'textbox', options: {required: false, readonly: true}}},
    {
        title: '单据类型', field: 'billType', editor: {
            type: 'combobox', options: {
                url: 'billType/listQuery',
                queryParams: {storageId: 1, accessMode: -1},
                method: 'GET',
                textField: 'billTypeName', valueField: 'id',
                panelHeight: 200,
                required: true,
                onLoadSuccess: function () {
                    $(this).combobox('options').limitToList = true;
                    let _data = $(this).combobox('getData') || [];
                    let _opts = $(this).combobox('options');
                    if (_data instanceof Array && !$(this).combobox('getValue') && _data.length > 0) {
                        for (let i of _data) {
                            if (i['isSelected']) {
                                $(this).combobox('setValue', i[_opts.valueField]);
                                break;
                            }
                        }
                    }
                }
            }
        }
    },
    {
        title: '供应商', field: 'supplierId', editor: {
            type: 'combobox', options: {
                url: 'supplier/listQuery',
                method: 'GET',
                textField: 'supplierName', valueField: 'id',
                panelHeight: 200,
                required: true,
                onLoadSuccess: function () {
                    $(this).combobox('options').limitToList = true;
                }
            }
        }
    },
    {
        title: '原料规格', field: 'materialSpec', editor: {
            type: 'combobox', options: {
                url: 'specification/listQuery',
                method: 'GET',
                textField: 'specName',
                valueField: 'specName',
                panelHeight: 200,
                required: true,
            }
        }
    },
    {title: '批号', field: 'batchNum', editor: {type: 'textbox', options: {required: false}}},
    {title: '件数', field: 'boxAmount', editor: {type: 'numberbox', options: {precision: 1, required: false}}},
    {
        title: '重量',
        id: 'inputKiloId',
        field: 'inputKilo',
        editor: {type: 'numberbox', options: {precision: 1, required: true}}
    },
    {
        title: '加工户', field: 'processCompany', id: 'processCompanyInput', editor: {
            type: 'combobox', options: {
                required: false,
                url: 'processCompany/listQuery',
                method: 'GET',
                textField: 'companyName',
                valueField: 'companyName',
                onLoadSuccess: function () {
                    let _data = $(this).combobox('getData') || [];
                    let valueField = $(this).combobox('options').valueField;
                    if (!$(this).combobox('getValue'))
                        for (let i of _data) {
                            if (i['isSelected']) {
                                $(this).combobox('setValue', i[valueField]);
                                break;
                            }
                        }
                }
            }
        }
    },
    {title: '经手人', field: 'handlerName', editor: {type: 'textbox', options: {required: false}}},
    {title: '备注', field: 'remarks', editor: {type: 'textbox', options: {required: false}}},
    {
        title: '制单人',
        field: 'createUserId',
        editor: {
            type: 'combobox',
            options: {
                readonly: true,
                url: 'sysUser/query',
                method: 'GET',
                textField: 'userName',
                valueField: 'id',
                onLoadSuccess: function () {
                    $(this).combobox('options').limitToList = true;
                }
            }
        }
    },
];

function setStatus(index) {
    let msg = {
        'tab-1': ['新增付款', '修改付款'],
        'tab0': ['新增出库', '新增入库'],
        'tab1': ['新增出库', '新增入库']
    };
    setTimeout(function () {
        $('#north').find('a[class*="easyui-linkbutton"]').each(function (item, i) {
            let text = $(i).linkbutton('options').text;
            if (msg[`tab${index}`] == undefined) return false;
            if (msg[`tab${index}`].indexOf(text) > -1) {
                $(i).linkbutton('disable');
            } else {
                $(i).linkbutton('enable');
            }
        })
    }, 0);
    if (index >= 0) {
        $('#state').switchbutton('enable');
    } else {
        $('#state').switchbutton('disable');
    }
}

//  应收应付 - 应付管理 - 应付款
function grid_4() {
    let SUFFIX = "_c";
    let batch_num = new kendo.data.DataSource({data: []});
    let handler_name = new kendo.data.DataSource({data: []});
    let supplier_name = new kendo.data.DataSource({data: []});
    let order_code = new kendo.data.DataSource({data: []});
    let material_spec = new kendo.data.DataSource({data: []});
    let dataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "materialOrder/report/accountpayable",
                dataType: "json",
                type: "GET",
                data: {
                    start: $('#start').datebox('getValue'),
                    end: $('#end').datebox('getValue'),
                    supplierName: $('#contactCompanyId').combobox('getValue'),
                    value: $('#state').switchbutton('options').checked ? 0 : 1
                    // textField: $('#column').combobox('getValue'),
                    // valueField: $('#value').textbox('getValue'),
                }
            }
        },
        schema: {
            model: {
                id: 'id',
                fields: {
                    billdate: {type: "date"},
                    box_amount: {type: "number"},
                    input_kilo: {type: "number"},
                    price: {type: "number"},
                    money: {type: "number"},
                    accoumlatedtoday: {type: "number"},
                    ticket_money: {type: "number"},
                }
            }
        },
        aggregate: [
            {field: "input_kilo", aggregate: "sum"},
            {field: "money", aggregate: "sum"},
            {field: "box_amount", aggregate: "sum"},
            {field: "ticket_money", aggregate: "sum"},
        ],
        change: function (e) {
            let data = this.data();
            batch_num.data(unique(data, 'batch_num'));
            handler_name.data(unique(data, 'handler_name'));
            supplier_name.data(unique(data, 'supplier_name'));
            order_code.data(unique(data, 'order_code'));
            material_spec.data(unique(data, 'material_spec'));
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('disable')
                }
            })
            // $('body').find('th a[class="k-grid-filter"]').css({display: 'none'});
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('enable')
                }
            })
        }
    });
    let columns = [
        {field: "no", title: "#", filterable: false, template: "<span class='row_number'></span>", width: 40},
        {
            field: "id",
            title: '编号',
            width: 93,
            hidden: true,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
        },
        {
            field: "supplier_id",
            title: '供应商编号',
            width: 93,
            hidden: true,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
        },
        {
            field: "billdate",
            title: '单据日期',
            width: 85,
            format: "{0: yyyy-MM-dd}",
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            footerTemplate: '总计:',
            filterable: false,
        },
        {
            field: "supplier_name",
            title: '供应商',
            width: 93,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
            filterable: {multi: true, search: true, dataSource: supplier_name}
        },
        {
            field: "material_spec",
            title: '项目',
            width: 93,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
            filterable: {multi: true, search: true, dataSource: material_spec}
        },
        {
            field: "account_type",
            title: '类型',
            width: 93,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
        },
        {
            field: "type",
            title: '单据类型',
            width: 93,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
            filterable: false
        },
        {
            field: "is_send_directly",
            title: '直发',
            width: 93,
            template: item => item['is_send_directly'] == '是' ? `<input type="checkbox" checked onclick="return false;">` : '',
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
        },
        {
            field: "process_company",
            title: '加工户',
            width: 93,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
        },
        {
            field: "batch_num",
            title: '批次号',
            width: 93,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
        },
        {
            field: "input_kilo",
            title: '重量',
            width: 93,
            template: item => item['input_kilo'] ? parseFloat(item['input_kilo']).toFixed(1) : '',
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
            filterable: false,
        },
        {
            field: "box_amount",
            title: '件数',
            width: 93,
            template: item => item['box_amount'] ? parseFloat(item['box_amount']).toFixed(1) : '',
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
            filterable: false,
        },
        {
            field: "price",
            title: '单价',
            width: 93,
            template: item => item['price'] ? parseFloat(item['price']).toFixed(2) : '',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
            filterable: false,
        },
        {
            field: "money",
            title: '金额',
            width: 93,
            template: item => item['money'] ? parseFloat(item['money']).toFixed(2) : '',
            footerTemplate: '#=kendo.format("{0:n2}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
            filterable: false,
        }, {
            field: "ticket_money",
            title: '发票金额',
            width: 93,
            template: item => item['ticket_money'] ? parseFloat(item['ticket_money']).toFixed(2) : '',
            footerTemplate: '#=kendo.format("{0:n2}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
            filterable: false,
        },
        {
            field: "accoumlatedtoday",
            title: '本日累计',
            width: 93,
            template: item => item['accoumlatedtoday'] ? parseFloat(item['accoumlatedtoday']).toFixed(2) : '',
            footerAttributes: {'style': 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },
        {
            field: "remarks",
            title: '备注',
            width: 93,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'},
            filterable: false,
        },
    ];
    let grid = $("#v_grid_c").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: {
            extra: false
        },
        dataSource: dataSource,
        columnMenu: false,
        excel: {
            fileName: "原料应付款.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        height: '99%',
        pageable: {
            pageSize: 200
        },
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });
        },
        columnHide: function (e) {
            //列隐藏事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
        },
        columnShow: function (e) {
            //列显示事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, false, null, SUFFIX);
        },
        columnResize: function (e) {
            //  列伸缩事件
            let field = e.column.field;
            let newWidth = e.newWidth;
            if (newWidth < 20) {
                columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
            } else {
                columnResizeEvent($('body').data('menu_id'), field, newWidth, null, null, SUFFIX);
            }
        },
        columnReorder: function (e) {
            //  列拖动事件
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex);
            let menuId = $('body').data('menu_id');
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNum: i,
                        sysMenuId: menuId,
                        field: newColumns[i]['field'] + SUFFIX
                    });
            }
            $.ajax({
                url: 'sysUserTableConfig/modify/reorder',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    let grid01 = $('#v_grid_c').data('kendoGrid');
    loadOptions(grid01, columns, SUFFIX, $('body').data('menu_id'));
    grid01.setOptions({
        columns: columns
    });
    grid.on('dblclick', 'tr', function (e) {
        //  双击打开原单
        let kGrid = $("#v_grid_c").data("kendoGrid");
        let dataItem = kGrid.dataItem(e.currentTarget);
        if (dataItem == undefined) {
            $.messager.alert('提示', '未选中!', 'warning');
            return;
        }
        if (dataItem['id'])
            btn_modify_payment();
    });
}

//  应收应付 - 应付管理 - 已付款
function grid_5() {
    let SUFFIX = "_d";
    let batch_num = new kendo.data.DataSource({data: []});
    let billtype = new kendo.data.DataSource({data: []});
    let client_name = new kendo.data.DataSource({data: []});
    let payable_type = new kendo.data.DataSource({data: []});
    let dataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "materialOrder/report/accountpayment",
                dataType: "json",
                type: "GET",
                data: {
                    start: $('#start').datebox('getValue'),
                    end: $('#end').datebox('getValue'),
                    supplierName: $('#contactCompanyId').combobox('getValue'),
                    value: $('#state').switchbutton('options').checked ? 0 : 1
                    // textField: $('#column').combobox('getValue'),
                    // valueField: $('#value').textbox('getValue'),
                }
            }
        },
        schema: {
            model: {
                id: 'id',
                fields: {
                    bill_date: {type: "date"},
                    money: {type: "number"},
                }
            }
        },
        aggregate: [
            {field: "money", aggregate: "sum"},
            {field: "input_money", aggregate: "sum"},
        ],
        change: function (e) {
            let data = this.data();
            batch_num.data(unique(data, 'batch_num'));
            billtype.data(unique(data, 'billtype'));
            client_name.data(unique(data, 'client_name'));
            payable_type.data(unique(data, 'payable_type'));
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('disable')
                }
            })
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('enable')
                }
            })
        }
    });
    let columns = [
        {field: "no", title: "#", filterable: false, template: "<span class='row_number'></span>", width: 40},
        {
            field: "id",
            title: '编号',
            width: 93,
            hidden: true,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
        },
        {
            field: "supplier_id",
            title: '供应商编号',
            width: 93,
            hidden: true,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
        },
        {
            field: "bill_date",
            title: '单据日期',
            width: 85,
            format: "{0: yyyy-MM-dd}",
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            footerTemplate: '总计:',
            filterable: false,
        },
        {
            field: "client_name",
            title: '供应商',
            width: 93,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
            filterable: {multi: true, search: true, dataSource: client_name}
        },
        {
            field: "billtype",
            title: '项目',
            width: 93,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
            filterable: {multi: true, search: true, dataSource: billtype}
        },
        {
            field: "payable_type",
            title: '付款类型',
            width: 93,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
            filterable: {multi: true, search: true, dataSource: payable_type}
        },
        {
            field: "money",
            title: '金额',
            width: 93,
            template: item => item['money'] ? parseFloat(item['money']).toFixed(2) : '',
            footerTemplate: '#=kendo.format("{0:n2}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:center;white-space:nowrap;text-overflow:ellipsis;'},
            filterable: false,
        },
        {
            field: "billmemo",
            title: '备注',
            width: 93,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'},
            filterable: false,
        },
    ];
    let grid = $("#v_grid_d").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: {
            extra: false
        },
        dataSource: dataSource,
        columnMenu: false,
        excel: {
            fileName: "已付款.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        height: '99%',
        pageable: {
            pageSize: 200
        },
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });
        },
        columnHide: function (e) {
            //列隐藏事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
        },
        columnShow: function (e) {
            //列显示事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, false, null, SUFFIX);
        },
        columnResize: function (e) {
            //  列伸缩事件
            let field = e.column.field;
            let newWidth = e.newWidth;
            if (newWidth < 20) {
                columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
            } else {
                columnResizeEvent($('body').data('menu_id'), field, newWidth, null, null, SUFFIX);
            }
        },
        columnReorder: function (e) {
            //  列拖动事件
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex);
            let menuId = $('body').data('menu_id');
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNum: i,
                        sysMenuId: menuId,
                        field: newColumns[i]['field'] + SUFFIX
                    });
            }
            $.ajax({
                url: 'sysUserTableConfig/modify/reorder',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    let grid01 = $('#v_grid_d').data('kendoGrid');
    loadOptions(grid01, columns, SUFFIX, $('body').data('menu_id'));
    grid01.setOptions({
        columns: columns
    });
    grid.on('dblclick', 'tr', function (e) {
        //  双击打开原单
        // let kGrid = $("#v_grid_d").data("kendoGrid");
        // let dataItem = kGrid.dataItem(e.currentTarget);
        // if (dataItem == undefined) {
        //     $.messager.alert('提示', '未选中!', 'warning');
        //     return;
        // }

    });
}

function onSelect(title, index) {
    setStatus(index);
    switch (index) {
        case 0:
            if ($('#v_grid_c').data('kendoGrid') == undefined) {
                grid_4();
            }
            break;
        case 1:
            if ($('#v_grid_d').data('kendoGrid') == undefined) {
                grid_5();
            }
            break;
    }
}

function btn_cancel_filter() {
    switch (getCurrentIndex()) {
        case 0:
            $('#v_grid_c').data('kendoGrid').dataSource.filter({});
            break;
        case 1:
            $('#v_grid_d').data('kendoGrid').dataSource.filter({});
            break;
    }
}

function btn_search() {
    function setCol(ele, show = []) {
        let kGrid = ele.data('kendoGrid');
        let columns = kGrid.columns;
        let checked = $('#state').switchbutton('options').checked;
        if (!checked)
            for (let col of columns) {
                if (col['field'] && show.indexOf(col['field']) == -1) {
                    kGrid.hideColumn(col);
                } else if (col['field']) {
                    kGrid.showColumn(col);
                }
            }
        else {
            for (let col of columns) {
                if (col['title'] && col['title'].indexOf('编号') > -1)
                    kGrid.hideColumn(col);
                else
                    kGrid.showColumn(col);
            }
        }
    }

    function research(index) {
        switch (index) {
            case 0:
                if ($('#v_grid_c').data('kendoGrid') != undefined) {
                    $('#v_grid_c').data('kendoGrid').dataSource.read({
                        start: $('#start').datebox('getValue'),
                        end: $('#end').datebox('getValue'),
                        supplierName: $('#contactCompanyId').combobox('getValue'),
                        value: $('#state').switchbutton('options').checked ? 0 : 1
                        // textField: $('#column').combobox('getValue'),
                        // valueField: $('#value').textbox('getValue'),
                    });
                    setCol($('#v_grid_c'), ['#', 'money', 'supplier_name']);
                }
                break;
            case 1:
                if ($('#v_grid_d').data('kendoGrid') != undefined) {
                    $('#v_grid_d').data('kendoGrid').dataSource.read({
                        start: $('#start').datebox('getValue'),
                        end: $('#end').datebox('getValue'),
                        supplierName: $('#contactCompanyId').combobox('getValue'),
                        value: $('#state').switchbutton('options').checked ? 0 : 1
                        // textField: $('#column').combobox('getValue'),
                        // valueField: $('#value').textbox('getValue'),
                    });
                    setCol($('#v_grid_d'), ['#', 'money', 'client_name']);
                }
                break;
        }
    }

    for (let i = 0; i < 2; i++) {
        research(i);
    }
    setStatus(getCurrentIndex());
}

function btn_add() {
    let param = {};
    if (getCurrentIndex() == 1) {
        let kGrid = getSelectedGrid();
        let dataItem = kGrid.dataItem(kGrid.select());
        if (dataItem != undefined) {
            param.batchNum = dataItem['batch_num'];
            param.materialSpec = dataItem['material_spec'];
            param.supplierId = dataItem['supplier_id'];
        }
    }
    openDialog(param);
    $.formDialog.enableBtn(['保存', '关闭']);
}

function btn_add_outbound(param = {}) {
    param.orderDate = getCurrentDate();
    if (getCurrentIndex() == 1) {
        let kGrid = $("#v_grid_a").data("kendoGrid");
        let dataItem = kGrid.dataItem(kGrid.select());
        if (dataItem == undefined) {
            $.messager.alert('提示', '请选中库存！！', 'warning');
            return;
        }
        param.batchNum = dataItem['batch_num'];
        param.materialSpec = dataItem['material_spec'];
        param.supplierId = dataItem['supplier_id'];
        if ($('#processCompanyInput').length > 0) {
            let _data = $('#processCompanyInput').combobox('getData') || [];
            for (let i of _data) {
                if (i['isSelected']) {
                    let valueField = $('#processCompanyInput').combobox('options').valueField;
                    param.processCompany = i[valueField];
                    break;
                }
            }
        }
    }
    openOutboundDialog(param);
    $.formDialog.enableBtn(['保存', '关闭']);
}

function openDialog(loadData) {
    $.formDialog.open({
        columns: materialColumns,
        onOpen: function () {
            $('#inputKiloId').numberbox('textbox').bind('keyup', function (e) {
                let price = $('#priceId').numberbox('getValue') || 0;
                let _value = $(this).val();
                $('#inputMoneyId').numberbox('setValue', price * _value);
            })
            $('#priceId').numberbox('textbox').bind('keyup', function (e) {
                let qty = $('#inputKiloId').numberbox('getValue') || 0;
                let _value = $(this).val();
                $('#inputMoneyId').numberbox('setValue', qty * _value);
            });
            $('.form-dialog-edit').find('.form-row:visible').eq(0).css({'margin-top': '10px'});
        },
        loadData: loadData,
        mode: '原料收货',
        width: 424,
        height: 587,
        buttons: [],
        toolbar: [
            {
                text: '新增', iconCls: 'icon-add', handler: e => {
                    $('.form-dialog-edit').eq(0).dialog('panel').find('form').form('clear');
                    $.formDialog.enableBtn(['保存', '关闭']);
                    $.formDialog.enableEditing();
                    $.formDialog.close();
                    btn_add();
                }
            },
            {
                text: '修改', iconCls: 'icon-edit', handler: e => {
                    $.formDialog.enableBtn(['保存', '关闭']);
                    $.formDialog.enableEditing();
                }
            },
            {
                text: '保存', iconCls: 'icon-save', handler: e => {
                    let url = '';
                    let formData = $('.form-dialog-edit').eq(0).dialog('panel').find('form').serializeObject();
                    if (formData['id']) {
                        url = 'materialOrder/updateSelective';
                    } else {
                        url = 'materialOrder/insertSelective';
                    }
                    $('.form-dialog-edit').eq(0).dialog('panel').find('form').form('submit', {
                        url: url,
                        success: function (data) {
                            data = eval(`(${data})`);
                            if (data.success) {
                                $.formDialog.disableBtn(['保存']);
                                $.formDialog.disableEditing();
                                $('.form-dialog-edit').eq(0).dialog('panel').find('form').form('load', data.data);
                                btn_search();
                                $.messager.show({title: '提示', msg: data.message});
                            } else {
                                $.messager.alert('提示', data.message, 'error');
                            }
                        }
                    });
                }
            },
            {
                text: '复制', iconCls: 'icon-page_copy', handler: e => {
                    $('.form-dialog-edit').eq(0).dialog('panel').find('form').form('load', {
                        id: null
                    });
                    $.formDialog.enableEditing();
                    $.formDialog.enableBtn(['保存', '关闭']);
                }
            },
            {
                text: '作废', iconCls: 'icon-cancel', handler: e => {
                    $.messager.confirm('提示', '是否作废？', function (r) {
                        if (r) {
                            let formData = $('.form-dialog-edit').find('form').serializeObject();
                            if (!formData['id']) {
                                $.messager.alert('提示', '单据未保存!', 'warning');
                                return;
                            }
                            $.ajax({
                                url: 'materialOrder/cancelByPk',
                                data: {id: formData.id},
                                type: 'POST',
                                dataType: 'json',
                                success: function (data) {
                                    if (data.success) {
                                        $.formDialog.close();
                                        btn_search();
                                        $.messager.show({title: '提示', msg: data.message});
                                    } else {
                                        $.messager.alert('提示', data.message, 'error');
                                    }
                                }
                            });
                        }
                    })
                }
            },
            {
                text: '关闭', iconCls: 'icon-no', handler: e => {
                    $('.form-dialog-edit').eq(0).dialog('close');
                }
            }]
    })
}

function openDialogByOpts(opts) {
    $.formDialog.open(opts);
}

function openOutboundDialog(loadData) {
    $.formDialog.open({
        columns: materialOutboundColumns,
        onOpen: function () {
            $('.form-dialog-edit').find('.form-row:visible').eq(0).css({'margin-top': '10px'});
        },
        loadData: loadData,
        mode: '原料领料',
        width: 424,
        height: 587,
        buttons: [],
        toolbar: [
            {
                text: '新增', iconCls: 'icon-add', handler: e => {
                    $('.form-dialog-edit').eq(0).dialog('panel').find('form').form('clear');
                    $.formDialog.enableBtn(['保存', '关闭']);
                    $.formDialog.enableEditing();
                    $.formDialog.close();
                    btn_add_outbound();
                }
            },
            {
                text: '修改', iconCls: 'icon-edit', handler: e => {
                    $.formDialog.enableBtn(['保存', '关闭']);
                    $.formDialog.enableEditing();
                }
            },
            {
                text: '保存', iconCls: 'icon-save', handler: e => {
                    let url = '';
                    let formData = $('.form-dialog-edit').eq(0).dialog('panel').find('form').serializeObject();
                    if (formData['id']) {
                        url = 'materialOrder/updateSelective';
                    } else {
                        url = 'materialOrder/insertSelective';
                    }

                    if (getCurrentIndex() == 1) {
                        let kGrid = $("#v_grid_a").data("kendoGrid");
                        let dataItem = kGrid.dataItem(kGrid.select());
                        let storageKilo = dataItem['input_kilo'] || 0;
                        let inputKilo = formData['inputKilo'] || 0;
                        if (dataItem != undefined) {
                            if (storageKilo < inputKilo) {
                                $.messager.confirm('提示', '超过库存，是否继续？', function (r) {
                                    if (r) {
                                        ex();
                                    }
                                });
                            } else {
                                ex();
                            }
                        }
                    }

                    function ex() {
                        $('.form-dialog-edit').eq(0).dialog('panel').find('form').form('submit', {
                            url: url,
                            success: function (data) {
                                data = eval(`(${data})`);
                                if (data.success) {
                                    $.formDialog.disableBtn(['保存']);
                                    $.formDialog.disableEditing();
                                    $('.form-dialog-edit').eq(0).dialog('panel').find('form').form('load', data.data);
                                    btn_search();
                                    $.messager.show({title: '提示', msg: data.message});
                                } else {
                                    $.messager.alert('提示', data.message, 'error');
                                }
                            }
                        });
                    }

                }
            },
            {
                text: '复制', iconCls: 'icon-page_copy', handler: e => {
                    $('.form-dialog-edit').eq(0).dialog('panel').find('form').form('load', {
                        id: null
                    });
                    $.formDialog.enableEditing();
                    $.formDialog.enableBtn(['保存', '关闭']);
                }
            },
            {
                text: '作废', iconCls: 'icon-cancel', handler: e => {
                    $.messager.confirm('提示', '是否作废？', function (r) {
                        if (r) {
                            let formData = $('.form-dialog-edit').find('form').serializeObject();
                            if (!formData['id']) {
                                $.messager.alert('提示', '单据未保存!', 'warning');
                                return;
                            }
                            $.ajax({
                                url: 'materialOrder/cancelByPk',
                                data: {id: formData.id},
                                type: 'POST',
                                dataType: 'json',
                                success: function (data) {
                                    if (data.success) {
                                        $.formDialog.close();
                                        btn_search();
                                        $.messager.show({title: '提示', msg: data.message});
                                    } else {
                                        $.messager.alert('提示', data.message, 'error');
                                    }
                                }
                            });
                        }
                    })
                }
            },
            {
                text: '关闭', iconCls: 'icon-no', handler: e => {
                    $('.form-dialog-edit').eq(0).dialog('close');
                }
            }]
    })
}

function btn_print() {
    let reportlets = [];
    $.get('customize/getDatabase', {}, data => {
        if (data.success) {
            switch (getCurrentIndex()) {
                case 0:
                    if (!$('#contactCompanyId').combobox('getValue')) {
                        $.messager.alert('提示', '请选择客户再打印！', 'warning');
                        return;
                    }
                    reportlets.push({
                        reportlet: `${data.data}/应付款序时表打印.cpt`,
                        Sdate: $('#start').datebox('getValue'),
                        Edate: $('#end').datebox('getValue'),
                        clientName: $('#contactCompanyId').combobox('getValue') || '',
                        database: data.data
                    });
                    window.parent.FR.doURLPDFPrint({
                        url: $(window.parent.document.body).data('report_url'),
                        isPopUp: false,
                        data: {
                            reportlets: reportlets
                        }
                    })
                    break;
                case 1:
                    if (!$('#contactCompanyId').combobox('getValue')) {
                        $.messager.alert('提示', '请选择客户再打印！', 'warning');
                        return;
                    }
                    reportlets.push({
                        reportlet: `${data.data}/已付款序时表打印.cpt`,
                        Sdate: $('#start').datebox('getValue'),
                        Edate: $('#end').datebox('getValue'),
                        clientName: $('#contactCompanyId').combobox('getValue') || '',
                        database: data.data
                    });
                    window.parent.FR.doURLPDFPrint({
                        url: $(window.parent.document.body).data('report_url'),
                        isPopUp: false,
                        data: {
                            reportlets: reportlets
                        }
                    })
                    break;
            }
        }
    }, 'json');
}

function btn_open_column_list() {
    let kendoGridID = '#v_grid';
    switch (getCurrentIndex()) {
        case 0:
            kendoGridID = '#v_grid_c';
            break;
        case 1:
            kendoGridID = '#v_grid_d';
            break;
    }
    let options = $(kendoGridID).data('kendoGrid').getOptions().columns;
    if ($('#btn_open_column_list').length <= 0) {
        let div = $(`<div data-options="
                    resizable:true,iconCls:'icon-text_columns',width:200,height:300,modal:true,title:'列',
                    onClose:function(){$(this).dialog('destroy')}" 
                          class="easyui-dialog" id="btn_open_column_list">
                   </div>`);
        let form = $('<form style="width: 100%;height: 100%;"></form>')
        for (let i of options) {
            if (i.field) {
                let checkbox = $(`<div style="width: 100%;height: auto;padding: 5px;">
                <input class="easyui-checkbox" name="${i.field}" data-options="label:'${i.title}',
                labelWidth:120,value:true,name:'${i.field}'">
                </div>`);
                form.append(checkbox);
            }
        }
        let container = $(`<div></div>`);
        form.appendTo(div);
        div.appendTo(container);
        $('body').append(container);
        $.parser.parse($('#btn_open_column_list').parent());
        let formData = {};
        options.map(item => {
            formData[item['field']] = item['hidden'] == undefined ? true : !item['hidden'];
        })
        $('#btn_open_column_list form').eq(0).form('load', formData);
        $('#btn_open_column_list form .easyui-checkbox').each(function () {
            //  绑定事件
            $(this).checkbox({
                onChange: function (checked) {
                    let opts = $(this).checkbox('options');
                    if (checked) {
                        $(kendoGridID).data('kendoGrid').showColumn(opts.name);
                    } else {
                        $(kendoGridID).data('kendoGrid').hideColumn(opts.name);
                    }
                }
            })
        })
    } else {
        $('#btn_open_column_list').dialog('open');
    }
}

function btn_export_excel() {
    getSelectedGrid().saveAsExcel();
}

function btn_close() {
    window.parent.closeTab();
}

function btn_add_payment() {
    let columns = [
        {
            field: 'clientName',
            title: '供应商',
            editor: {
                type: 'combobox', options: {
                    url: 'supplier/listQuery',
                    method: 'GET', queryParams: {state: 1},
                    textField: 'supplierName', valueField: 'supplierName',
                    panelHeight: 200,
                    required: true,
                    onLoadSuccess: function () {
                        $(this).combobox('options').limitToList = true;
                        if (!$(this).combobox('getValue')) {
                            let loadData = $(this).combobox('getData') || [];
                            let opts = $(this).combobox('options');
                            if (loadData.length > 0) {
                                if ($('#contactCompanyId').combobox('getValue')) {
                                    $(this).combobox('setValue', $('#contactCompanyId').combobox('getValue'));
                                } else {
                                    $(this).combobox('setValue', loadData[0][opts.valueField]);
                                }
                            }
                        }
                    }
                }
            }
        },
        {
            field: 'billDate',
            title: '日期',
            editor: {type: 'datebox', options: {required: true, value: getCurrentDate()}}
        },
        {
            field: 'billtype',
            title: '项目',
            editor: {
                type: 'combobox', options: {
                    required: true,
                    data: [{value: '付款'}, {value: '付款调整'}, {value: '开票'}],
                    textField: 'value',
                    valueField: 'value',
                    limitToList: true,
                    panelHeight: 'auto',
                    onChange: function (newVal, oldVal) {
                        if (newVal == '付款调整' || newVal == '开票') {
                            $('#collectiontypeInput').combobox('clear');
                            $('#collectiontypeInput').combobox('disable');
                        } else {
                            $('#collectiontypeInput').combobox('enable');
                        }
                    }
                }
            }
        },
        {
            field: 'money',
            title: '金额',
            editor: {type: 'numberbox', options: {precision: 2, required: true,}}
        },
        {
            field: 'payableType',
            id: 'collectiontypeInput',
            title: '付款类型',
            editor: {
                type: 'combobox', options: {
                    data: [{value: '转账'}, {value: '承兑'}, {value: '现金'}],
                    value: '转账',
                    textField: 'value',
                    valueField: 'value',
                    limitToList: true,
                    panelHeight: 'auto'
                }
            }
        },
        {
            field: 'billmemo',
            title: '备注',
            editor: {type: 'textbox', options: {multiline: true, height: 100}}
        }
    ];
    let loadData = {};
    openDialogByOpts({
        loadData: loadData,
        columns: columns,
        height: 380,
        width: 330,
        mode: '新增付款',
        buttons: [{
            text: '保存', iconCls: 'icon-save', handler: e => {
                let dialog = $('.form-dialog-edit');
                if (!$(dialog.find('form')).form('validate')) {
                    return;
                }
                let param = $(dialog.find('form')).serializeObject();
                let url = 'materialAccountPayable/insertSelective';
                //  修改
                $.messager.progress({
                    title: '',
                    msg: '请稍等...',
                    interval: 5000
                });
                $.ajax({
                    url: url,
                    type: 'POST',
                    dataType: 'json',
                    data: param,
                    success: function (data) {
                        if (data.success) {
                            btn_search();
                            $.formDialog.close();
                            $.messager.show({title: '提示', msg: data.message});
                        } else {
                            $.messager.alert('提示', data.message, 'warning');
                        }
                    },
                    complete: function () {
                        $.messager.progress('close');
                    }
                })
            }
        }, {
            text: '取消', iconCls: 'icon-cancel', handler: e => {
                $.formDialog.close();
            }
        }]
    });
}

function btn_modify_payment() {
    let kGrid = $('#v_grid_c').data('kendoGrid');
    let dataItem = kGrid.dataItem(kGrid.select());
    if (dataItem == undefined || !dataItem['id']) {
        $.messager.alert('提示', '请选中付款或付款调整', 'warning');
        return;
    }
    let columns = [
        {
            field: 'id',
            title: '编号',
        },
        {
            field: 'clientName',
            title: '客户',
            editor: {
                type: 'combobox', options: {
                    url: 'supplier/listQuery',
                    method: 'GET', queryParams: {state: 1},
                    textField: 'supplierName', valueField: 'supplierName',
                    panelHeight: 200,
                    required: true,
                    onLoadSuccess: function () {
                        $(this).combobox('options').limitToList = true;
                    }
                }
            }
        },
        {
            field: 'billDate',
            title: '日期',
            editor: {type: 'datebox', options: {required: true, value: getCurrentDate()}}
        },
        {
            field: 'billtype',
            title: '项目',
            editor: {
                type: 'combobox', options: {
                    required: true,
                    data: [{value: '付款'}, {value: '付款调整'}, {value: '开票'}],
                    textField: 'value',
                    valueField: 'value',
                    panelHeight: 'auto',
                    limitToList: true,
                    onChange: function (newVal, oldVal) {
                        if (newVal == '付款调整' || newVal == '开票') {
                            $('#collectiontypeInput').combobox('clear');
                            $('#collectiontypeInput').combobox('disable');
                        } else {
                            $('#collectiontypeInput').combobox('enable');
                        }
                    }
                }
            }
        },
        {
            field: 'money',
            title: '金额',
            editor: {type: 'numberbox', options: {precision: 2, required: true,}}
        },
        {
            field: 'payableType',
            id: 'collectiontypeInput',
            title: '付款类型',
            editor: {
                type: 'combobox', options: {
                    data: [{value: '转账'}, {value: '承兑'}, {value: '现金'}],
                    textField: 'value',
                    valueField: 'value',
                    limitToList: true,
                    panelHeight: 'auto'
                }
            }
        },
        {
            field: 'billmemo',
            title: '备注',
            editor: {type: 'textbox', options: {multiline: true, height: 100}}
        }
    ];
    openDialogByOpts({
        loadData: {
            id: dataItem['id'],
            billtype: dataItem['material_spec'],
            clientName: dataItem['supplier_name'],
            money: dataItem['material_spec'] == '开票' ? dataItem.ticket_money : -dataItem.money,
            billDate: kendo.toString(dataItem.billdate, 'yyyy-MM-dd'),
            payableType: dataItem['account_type'],
            billmemo: dataItem['remarks']
        },
        columns: columns,
        height: 380,
        width: 330,
        mode: '修改付款',
        buttons: [
            {
                text: '删除付款', iconCls: 'icon-remove', handler: e => {
                    $.messager.confirm('提示', '是否确定删除？删除后不可恢复!', function (r) {
                        if (r) {
                            $.messager.progress({
                                title: '',
                                msg: '请稍等...',
                                interval: 5000
                            });
                            let dialog = $('.form-dialog-edit');
                            let url = 'materialAccountPayable/deleteByPk';
                            let param = $(dialog.find('form')).serializeObject();
                            $.ajax({
                                url: url,
                                type: 'POST',
                                dataType: 'json',
                                data: {id: param['id'] || 0},
                                success: function (data) {
                                    if (data.success) {
                                        btn_search();
                                        $.formDialog.close();
                                        $.messager.show({title: '提示', msg: data.message});
                                    } else {
                                        $.messager.alert('提示', data.message, 'warning');
                                    }
                                },
                                complete: function () {
                                    $.messager.progress('close');
                                }
                            })
                        }
                    })
                }
            }, {
                text: '保存', iconCls: 'icon-save', handler: e => {
                    let dialog = $('.form-dialog-edit');
                    if (!$(dialog.find('form')).form('validate')) {
                        return;
                    }
                    let param = $(dialog.find('form')).serializeObject();
                    let url = 'materialAccountPayable/updateSelective';
                    //  修改
                    $.messager.progress({
                        title: '',
                        msg: '请稍等...',
                        interval: 5000
                    });
                    $.ajax({
                        url: url,
                        type: 'POST',
                        dataType: 'json',
                        data: param,
                        success: function (data) {
                            if (data.success) {
                                btn_search();
                                $.formDialog.close();
                                $.messager.show({title: '提示', msg: data.message});
                            } else {
                                $.messager.alert('提示', data.message, 'warning');
                            }
                        },
                        complete: function () {
                            $.messager.progress('close');
                        }
                    })
                }
            }, {
                text: '取消', iconCls: 'icon-cancel', handler: e => {
                    $.formDialog.close();
                }
            }],
        onOpen: function () {
            setTimeout(function () {
                $('.form-dialog-edit').dialog('panel').find('.l-btn').eq(0).css({float: 'left'});
            }, 0)
        }
    });
}

function getSelectedGrid() {
    let kendoGridID = '';
    switch (getCurrentIndex()) {
        case 0:
            kendoGridID = '#v_grid_c';
            break;
        case 1:
            kendoGridID = '#v_grid_d';
            break;
    }
    return $(kendoGridID).data('kendoGrid');
}

function stateChange(checked) {
    if (!checked && getCurrentIndex() == 3) {
        $('#contactCompanyId').combobox('clear');
        $('#contactCompanyId').combobox('disable');
        $('#start').datebox('disable');
        $('#end').datebox('disable');
    } else {
        $('#start').datebox('enable');
        $('#end').datebox('enable');
        $('#contactCompanyId').combobox('enable');
    }
    btn_search();
}

function getCurrentIndex() {
    let tab = $('#tabs').tabs('getSelected');
    let index = $('#tabs').tabs('getTabIndex', tab);
    return index;
}

//选中事件
function initCombobox(options) {
    var columns = options.columns;
    columns.splice(0, 1);
    $('#column').combobox({
        valueField: 'field',
        textField: 'title',
        data: columns,
        editable: false
    })
}